package birdsong.comm;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import birdsong.comm.ServerSideMessage.Type;

// ClientComm must receive nickname and message to be sended...
public class ClientCommImp implements ClientComm{

	// Server hostname and port
	private static final int SV_PORT = 8080;

	// Client variables.
	private Socket cl_socket;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private String sender;
	private ClientSideMessage csm;
	

	public ClientCommImp() {

	}

	@Override
	public void connect(String host, String nickname) throws UnknownHostException, IOException {
		this.sender = nickname;
		InetAddress sv_address = InetAddress.getByName(host);
		
		cl_socket = new Socket(sv_address, SV_PORT);

		System.out.println("Client socket: " + cl_socket);

		in = new ObjectInputStream(cl_socket.getInputStream());
		out = new ObjectOutputStream(cl_socket.getOutputStream());

		out.writeObject(new ServerSideMessageImp(sender, Type.CLIENT_CONNECTED, null));
		out.flush();		
	}

	@Override
	public boolean isConnected() {
		return !cl_socket.isClosed();
	}

	@Override
	public void disconnect() {
		// TODO Auto-generated method stub
		try {
			out.writeObject(new ServerSideMessageImp(sender, Type.CLIENT_DISCONNECTED, null));
			out.flush();
			cl_socket.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Override
	public ClientSideMessage getNextMessage() {
		// TODO Auto-generated method stub
		try {
			csm = (ClientSideMessage) in.readObject();
			in.reset();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return csm;
	}

	@Override
	public boolean hasNextMessage() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void sendBirdsongMessage(String birdsongMessage) {
		// TODO Auto-generated method stub
		try {		
			out.writeObject(new ServerSideMessageImp(sender, Type.BIRDSONG_MESSAGE, birdsongMessage));
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void follow(String nickname) {
		// TODO Auto-generated method stub
		try {
			out.writeObject(new ServerSideMessageImp(sender, Type.FOLLOW, nickname));
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void unfollow(String nickname) {
		// TODO Auto-generated method stub
		try {
			out.writeObject(new ServerSideMessageImp(sender, Type.UNFOLLOW, nickname));
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
